<?php
/**
 * 
 * @author ronnie  (comdeng@gmail.com)
 * @link    http://fillphp.com/
 * @date   2014-5-1
 * @file      Controller.php
 * @description 
 */
 
namespace fillphp\page;

require_once __DIR__.'/Response.php';
require_once dirname(__DIR__).'/helper/Helper.php';

class Controller
{
	/**
	 * 用来验证的字段
	 * @var array
	 */
	protected $valids = array();
	
	/**
	 * 请求
	 * @var \fillphp\page\Request
	 */
	protected $request;
	
	/**
	 * 模板路径
	 * @var string
	 */
	var $tplDir;
	
	function __construct()
	{
		if (defined('PAGE_ROOT')) {
			$this->tplDir = PAGE_ROOT;
		}
	}
	
	/**
	 * 设置请求对象
	 * @param \fillphp\page\Request $request
	 * @return \fillphp\page\Controller
	 */
	function setRequest($request)
	{
		$this->request = $request;
		return $this;
	}
	
	/**
	 * 重定向到指定页面
	 * @return \fillphp\page\Response
	 */
	protected function redirect($url, $code = STATUS_TEMPORARILY_MOVED)
	{
		if (in_array($code, array(STATUS_PERMANENTLY_MOVED, STATUS_TEMPORARILY_MOVED))) {
			throw new Exception(__NAMESPACE__.'\redirectCodeIllegal code='.$code);
		}
		$res = new Response('', $code);
		return $res->redirect($url);
	}
	
	protected function display($template, array $args = array())
	{
		$template = $this->tplDir.'/'.$template;
		if (!is_readable($template)) {
			throw new \Exception('\fillphp\page\view\tplNotReadable tpl:'.$template);
		}
		//TODO 需要实现view的自定义
		require_once dirname(__DIR__).'/view/FillView.php';
		$view = new \fillphp\view\FillView($this->request);
		$view->setArray($args);
		$content = $view->display($template);
		return new Response($content);
	}
	
	/**
	 * 
	 * @param string $name
	 * @return \fillphp\helper\ControllerHelper
	 */
	protected function helper($name)
	{
		return \fillphp\helper\Helper::getHelper($name, $this->request);
	}
}